﻿'use strict';

const readline = require('readline');  
var request = require('request');
var https = require('https');
var cheerio = require('cheerio');
var fs = require('fs');
var path = require('path');
var async = require("async");
var config = require("./config.js");
var getAndSaveFile = require("./fileGetAndSave.js");
var logger = require("./logger.js");

logger.info("应用启动。。。");
logger.info("请输入页面地址：");
readLineInput();

function readLineInput() {
    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });
    rl.on('line', function (input) {
        if (input.startsWith("http")) {
            getRequestionPage(input);
        }
    });

    rl.on('close', function () {
        console.log('程序结束');
        process.exit(0);
    });  
}

function getRequestionPage(urlPath) {

    if (!config.dirPath) {
        config.dirPath = "./images/";
    }

    var urls = [];

    request({
        url: urlPath,
        method: 'GET',
        gzip: true
    }, function (err, resp, body) {
            if (err) {
                logger.info("请求页面失败：" + url);
                console.error('[ERROR]Collection' + err);
                return;
            }

            let $ = cheerio.load(body);

            let title = $("title").text();
            logger.info("访问页面：" + title);

            let dirName = dirFilter(title);
            mkdirPath("\\Download\\" + dirName);

            $(".App-main img").each(function (index, item) {
                let imgSrc = $(this).attr('src');
                if (imgSrc.startsWith("http")) {
                    urls.push(imgSrc);
                    logger.info("解析到第 " + index + " 张图片：" + imgSrc);
                }
            });

            logger.info("图片数量：" + urls.length);

            async.mapLimit(urls, config.asyncThreadNum, function (url, callback) {
                getAndSavePic(dirName, url, callback);
            }, function (err, result) {
                    logger.log("成功获取图片数量：" + result.length);
                    //logger.error(err);
            });
            logger.info("完成任务");
    });
}

function getAndSavePic(title, imgSrc, callBack) {
    logger.info("获取图片：" + imgSrc);
    let imgPath = imgSrc.split("/");
    let imgName = imgPath[imgPath.length - 1].split("?")[0];

    try {
        let projectPath = path.join(process.cwd());
        //let reader = request(imgSrc).pipe(fs.createWriteStream(projectPath + "/" + title + "/" + imgName));
        //callBack(null, imgName);
        if (imgSrc.startsWith("https")) {
            imgSrc = imgSrc.replace("https", "http");
        }

        getAndSaveFile(imgSrc, projectPath + "\\Download\\" + title + "\\", imgName, function () {
            callBack(null, imgName);
        });
    } catch (e) {
        logger.error("图片文件获取失败");
        logger.error(e);
        callback(null);
    }
}


function mkdirPath(pathStr) {
    let projectPath = path.join(process.cwd());
    let tempDirArray = pathStr.split('\\');
    for (var i = 0; i < tempDirArray.length; i++) {
        projectPath = projectPath + '/' + tempDirArray[i];
        if (fs.existsSync(projectPath)) {
            let tempstats = fs.statSync(projectPath);
            if (!tempstats.isDirectory()) {
                fs.unlinkSync(projectPath);
                fs.mkdirSync(projectPath);
            }
        }
        else {
            fs.mkdirSync(projectPath);
        }
    }
    return projectPath;
}

function dirFilter(title) {
    var regex = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
    if (regex.test(title)) {
        var chinese = "";
        var flag = false;
        var filterChinese = "";
        for (var i = 0; i < title.length; i++) {
            chinese = title.substring(i, i + 1);
            flag = regex.test(chinese);
            if (flag) {
                filterChinese += chinese;
            }
        }

        return filterChinese;
    }
}